package com.leenmvc.core.security.service.core;

import com.leenmvc.core.annotation.TransactionMulti;
import com.leenmvc.core.annotation.validator.groups.AddGroup;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.TokenGenerator;
import com.leenmvc.core.security.User;
import com.leenmvc.core.security.dao.core.SysUserDao;
import com.leenmvc.core.security.dao.core.SysUserTokenDao;
import com.leenmvc.core.security.entity.core.SysUser;
import com.leenmvc.core.security.entity.core.SysUserToken;
import com.leenmvc.core.utils.security.PasswordUtils;
import com.leenmvc.core.utils.thread.ThreadLocalManager;
import com.leenmvc.core.utils.validator.ValidatorUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 用户服务层
 */
@Service
public class SysUserService extends BaseService<SysUser> {

    @Autowired
    private SysUserTokenDao sysUserTokenDao;

    @Autowired
    private SysUserDao sysUserDao;

    /**
     * 登录逻辑
     *
     * @param user
     * @return
     */
    public String login(SysUser user) {
        SysUserToken userToken = sysUserTokenDao.get("userId", user.getId());
        boolean success = false;
        if (userToken == null) {
            userToken = new SysUserToken();
            userToken.setUserId(user.getId());
            userToken.setToken(TokenGenerator.generateValue());
            userToken.setCreateDate(new Date());
            userToken.setUpdateDate(new Date());
            userToken.setExpireDate(new DateTime().plusDays(1).toDate());
            success = sysUserTokenDao.insert(userToken);
        } else {
            userToken.setUpdateDate(new Date());
            userToken.setExpireDate(new DateTime().plusDays(1).toDate());
            userToken.setToken(TokenGenerator.generateValue());
            success = sysUserTokenDao.update(userToken);
        }

        if (success) {
            user.setToken(userToken);
            String token = userToken.getToken();
            ThreadLocalManager.put("loginStatus", 1);
            return token;
        } else {
            ThreadLocalManager.setUser(new SysUser()); // 设置用户信息到本地线程变量
        }
        throw new BusinessException("登录失败！");
    }

    /**
     * token判断用户是否登录
     */
    public boolean isLogin(String token){
        if (token == null || "".equals(token)){
            return false;
        }
        SysUserToken userToken = sysUserTokenDao.get("token", token);
        if(userToken.getExpireDate().getTime() < System.currentTimeMillis()) {
            return false;
        }
        return true;
    }

    /**
     * 登出操作
     */
    @TransactionMulti
    public void loginOut() {
        SysUserToken token = User.getToken();
        Date date = new Date();
        token.setExpireDate(date);
        if (!sysUserTokenDao.update(token)) {
            throw new BusinessException("登出失败！");
        } else {
            ThreadLocalManager.put("loginOutStatus", 1);
        }
    }


    @Override
    public <T> boolean insert(T t) {
        SysUser sysUser = (SysUser) t;
        ValidatorUtils.validateEntity(sysUser, AddGroup.class);
        // 密码加密
        String pwd = PasswordUtils.encode(sysUser.getPassword());
        sysUser.setPassword(pwd);
        sysUser.setSuperAdmin(0);
        // 默认设置普通用户角色
        sysUser.setRoleId(717041517844426752L);
        return super.insert(sysUser);
    }


    @Override
    @TransactionMulti
    public <T> boolean update(T t) {
        SysUser sysUser = (SysUser) t;
        // 密码加密
//        if (sysUser.getPassword() != null) {
//            String pwd = PasswordUtils.encode(sysUser.getPassword());
//            sysUser.setPassword(pwd);
//        }
//        String pwd = PasswordUtils.encode(sysUser.getPassword());
//        sysUser.setPassword(pwd);
        return super.update(sysUser);
    }

}
